package com.sunday.common.netty.e5_Udp.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UdpServer {

    public static final int SERVER_PORT = 8822;

    public static void main(String[] args) {

        log.info("Begin to start UDP server on port: {}.....", SERVER_PORT);

        EventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(bossLoopGroup)
                    // NioDatagramChannel: 用于UDP
                    .channel(NioDatagramChannel.class)
                    // ChannelOption.AUTO_CLOSE: 一旦连接，就会自动关闭。 默认 false。
                    .option(ChannelOption.AUTO_CLOSE, true)
                    // ChannelOption.SO_BROADCAST 用于设置UDP广播模式。
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpServerHandler());

            ChannelFuture channelFuture = bootstrap.bind(SERVER_PORT).sync();
            log.info("UDP server started.");
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            bossLoopGroup.shutdownGracefully();
        }

    }

}
